<?php

  /* File:    lib/genlib.tx: assorted general functions
   * Type:    CMS function library
   * Author:  udo.schroeter@gmail.com
   * License: commercially licensed as part of the CMS package
   * Todo:    - do we really need all of those?
   * Changes: -
   */

  // start profiler time
  #$profiler_time_start = microtime();
  $profiler_last = getDefault($profiler_time_start, microtime());
  $profiler_report = array();
  
  function profile_point($text)
  {
    global $profiler_report, $profiler_time_start, $profiler_last;
    $thistime = microtime();
    $profiler_report[] = profiler_microtime_diff($thistime,$profiler_time_start).' '.
      profiler_microtime_diff($thistime,$profiler_last).' :: '.$text;
    $profiler_last = $thistime;
  }
  
  function profiler_microtime_diff($b, $a)
  {
    list($a_dec, $a_sec) = explode(" ", $a);
    list($b_dec, $b_sec) = explode(" ", $b);
    return number_format($b_sec - $a_sec + $b_dec - $a_dec, 4);
  }

  function criticalError($module, $message)
  {
    ob_start(); print_r($_REQUEST); $request = ob_get_clean();
    ob_start(); print_r($ENV); $env = ob_get_clean();   
    $err = array(
      'e_module' => $module,
      'e_message' => $message,
      'e_context' => $request,
      'e_env' => $env,
      'e_ip' => $ENV['REMOTE_ADDR'],
      );
    DB_UpdateDataset('errors', $err);
  }

  function cr2br($str)
  {
    return(preg_replace('#\r?\n#', '<br />', $str));
  }
  
  function cache_textout($name)
  {
    global $config;
    $filename = 'cache/'.$name;
    if (!file_exists($filename)) return(false);
    if (time()-filectime($filename) > $config['site.cache.timeout']) return(false);
    profile_point('cache-hit "'.$name.'", object age '.(time()-filectime($filename)).' sec');
    $fp = fopen($filename, 'rb');
    return(fpassthru($fp));
  }
  
  function cache_storetext($name, $content, $display = false)
  {
    global $config;
    @mkdir('cache', 0777);
    $filename = 'cache/'.$name;
    @unlink($filename);
    $open = fopen($filename, 'a+');
    fwrite($open, $content);
    fclose($open);
    chmod($filename, 0777);    
    if ($display) print($content);
  }
  
  function parse_timestamp($ts)
  {
    #format: Y-m-d H:i:s (SQL datetime format)
    $year = CutSegment('-', $ts);
    $month = CutSegment('-', $ts);
    $day = CutSegment(' ', $ts);
    $hour = CutSegment(':', $ts);
    $minute = CutSegment(':', $ts);
    $second = $ts;
    return(mktime($hour, $minute, $second, $month, $day, $year));
  }
  
  function logError($msg)
  {
    global $config;
    
    #logToFile('log/error.log', $msg);
    
    print('<div class="banner">'.$msg.'</div>');
  }

  function banner($text)
  {
    print('<div class="banner">'.$text.'</div>');    
  }

  function send_mail($to, $template, $params = array())
  {
    global $config;
    foreach($params as $k => $v) ${'_'.$k} = $v;
    ob_start();
    include($template);
    $content = ob_get_clean();
    mail($to, $subject, $content, $headers);
  }

  function feedTag($action, $controller, $type = 'RSS 2.0')
  {
    global $config;
    return('<link rel="alternate" '.
           'type="application/rss+xml" title="'.$type.
           '" href="'.$config['site.base'].actionUrl($action, $controller).'" />');
  }

  function actionUrl($action = '', $controller = '', $params = array())
  {
    global $config;
    $controller = getDefault($controller, $_REQUEST['controller']);
    $controller = getDefault($controller, $config['site.defaultcontroller']);
    $action = getDefault($action, $_REQUEST['action']);
    $action = getDefault($action, $config['site.defaultaction']);    
    
    if (!is_array($params))
      $params = stringParamsToArray($params);
    
    $p = '';
    foreach ($params as $k => $v)
    $p .= '/'.$k.'/'.$v;
    
    // the only reason we're including site.base here is that there's
    // a bug in IE that causes the browser to ignore the BASE tag
    // when javascript document.location is used :-(
    return($config['site.base'].$controller.'/'.$action.$p);
  }
  
  function stringParamsToArray($paramStr)
  {
    $result = array();
    foreach(explode(',', $paramStr) as $line)
    {
      $k = CutSegment('=', $line);
      $result[$k] = $line;	
    }
    return($result);
  }

  function make_link($title, $action = null, $controller = null, $params = array())
  {
    return('<a href="'.actionUrl($action, $controller, $params).'">'.htmlentities($title).'</a>');  
  }

  function execTemplate($templateFileName, $params = array())
  {
    foreach ($params as $k => $v) $$k = $v;
    ob_start();
    include($templateFileName);
    return(ob_get_clean());
  }

  // if $def1 is empty, use $def2
  function GetDefault(&$def1, $def2 = '', $zero_ok = false)
  {
    //if ($def=='0' && $zero_ok) return($def1);
    if (!isset($def1) || $def1=='')
    {
      if (!isset($def2))
        return '';
      else
        return $def2;
    }
    else
    {
      return $def1;
    }
  }
  
  // returns the path to the site's root folder
  function getBasePath($pathDepthModifier = 1)
  {
    global $config;
    $basePathToScript = $_SERVER['SCRIPT_NAME'];
    $pathInfo = $_SERVER['PATH_INFO'];
    $serverName = 'http://'.$_SERVER['SERVER_NAME'];
    $serverPort = getDefault($_SERVER['SERVER_PORT'], 80);

    $pathDepthModifier = getDefault($pathDepthModifier, 1);
    $pathInfoSegments = explode('/', $pathInfo);
    $basePathSegments = explode('/', $basePathToScript);
    $pathDepth = sizeof($pathInfoSegments)-1;
    for($cnt = 0; $cnt < $pathDepthModifier; $cnt++)
      unset($basePathSegments[sizeof($basePathSegments)-1]);
    $basePath = $serverName.':'.$serverPort.implode('/', $basePathSegments).'/';

    $config['site']['basepath'] = $basePath;
    $config['cms']['urlpath'] = $basePathToScript;
    $config['site']['server'] = $serverName;
    if ($config['site.ignoreport']) $serverPort = 80;
    $config['site']['port'] = $serverPort;
    //$_REQUEST['virtual'] = substr($pathInfo, 1);

    return($config['site']['basepath']);
  }

  // cut $cake at the first occurence of $segdiv, returns the slice
  function CutSegmentEx($segdiv, &$cake, &$found)
  {
    $p = strpos($cake, $segdiv);
    if ($p === false)
    {
      $result = $cake;
      $cake = '';
      $found = false;
    }
    else
    {
      $result = substr($cake, 0, $p);
      $cake = substr($cake, $p + strlen($segdiv));
      $found = true;
    }
    return $result;
  }

  // like CutSegmentEx(), but doesn't carry the $found result flag
  function CutSegment($segdiv, &$cake)
  {
    return(CutSegmentEx($segdiv, $cake, $found));
  }
  
  function stringListToStrings($stringList)
  {
    $result = array();
    foreach ($stringList as $k => $v)
    {
      if (trim($v) != '' && $k != '')
        $result[] = $k.'='.trim($v);
    }
    return($result);
  }
  
  function stringsToStringlist($stringArray)
  {
    $result = array();  
    if (is_array($stringArray))
      foreach ($stringArray as $line)
      {
        $key = CutSegment('=', $line);
        $result[$key] = trim($line);
      }
    return($result);
  }

  function textToStringList($text)
  {
    $list = explode("\n", $text);
    return(stringsToStringlist($list));
  }
  
  function stringlistToText($stringlist)
  {
    $list = stringlistToStrings($stringlist);
    return(implode("\n", $list));
  }

  // read a hash from a text file
  function readStringListFile($filename)
  {
    $fileContent = @file($filename);
    return(stringsToStringlist($fileContent));
  }

  // if this version of PHP doesn't support ob_get_clean, we'll define it here
  if (!is_callable('ob_get_clean'))
    include('lib/genlib-ob_get_clean.tx');

?>
